//
//  WBHomeViewController.swift
//  传智微博
//
//  Created by zuxi li on 2017/3/14.
//  Copyright © 2017年 lingtu. All rights reserved.
//

import UIKit

// 定义全局变量，尽量使用private 修饰， 否则到处可以访问
private let cellId = "cellId"

class WBHomeViewController: WBBaseViewController {
    
    
//    /// 微博数据数组
//    fileprivate lazy var statusList = [String]()
    
    
    /// 列表视图模型
    fileprivate lazy var listViewModel = WBStatusListViewModel()
    
    /// 加载数据
    override func loadData() {
        
        // 用网络工具加载微博数据
        /*
        // 2.006qtdcFiHOobDf42e3d01b90R5pqZ
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let params = ["access_token": "2.006qtdcFiHOobDf42e3d01b90R5pqZ"]
//        WBNetworkManager.shared.get(urlString, parameters: params, progress: nil, success: { (_, json) in
//            print(json ?? "")
//        }) { (_, error) in
//            print("网络请求失败 \(error)")
//        }
        WBNetworkManager.shared.request(URLString: urlString, parameters: params as [String : AnyObject]) { (json, isSuccess) in
            print(json ?? "")
        }
        */
        
        print("加载数据结束 \(self.listViewModel.statusList.last?.text)")
        listViewModel.loadStatus(pullup: self.isPullup) { (isSuccess, shouldRefresh) in
            
            
            // 结束刷新控件
            self.refreshControl?.endRefreshing()
            // 恢复上拉刷新标记
            self.isPullup = false
            // 刷新表格
            if shouldRefresh {
                self.tableView?.reloadData()
            }
            
        }
        WBNetworkManager.shared.statusList { (list, isSuccess) in
            print(list ?? "")
            
        }
//        print("开始加载数据 ")
//        // 模拟‘延时’加载数据
//        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
//            for i in 0..<15 {
//                if self.isPullup {
//                    // 将数据追加到底部
//                    self.statusList.append("上拉\(i)")
//                } else {
//                    // 将数据插入到数组的顶部
//                    self.statusList.insert(i.description, at: 0)
//                }
//                
//            }
//            
//            print("刷新表格")
//            // 结束刷新控件
//            self.refreshControl?.endRefreshing()
//            // 恢复上拉刷新标记
//            self.isPullup = false
//            // 刷新表格
//            self.tableView?.reloadData()
//        }
        
        
    }
    
    /// 显示好友
    @objc fileprivate func showFriends() {
        print(#function)
        let vc = WBDemoViewController()
//        vc.hidesBottomBarWhenPushed = true
        // push 的动作是 nav 做的
        navigationController?.pushViewController(vc, animated: true)
        
    }

}


// MARK: - 表格数据源方法, 具体的数据源方法实现，不需要 super
extension WBHomeViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//         return statusList.count
        return listViewModel.statusList.count
        
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // 1. 取cell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        // 2. 设置cell
//        cell.textLabel?.text = statusList[indexPath.row]
        cell.textLabel?.text = listViewModel.statusList[indexPath.row].text
        // 3. 返回cell
        return cell
    }
}

// MARK: - 设置界面
extension WBHomeViewController {
    /// 重写父类发方法
    override func setupTableView() {
        super.setupTableView()
        
        // 设置导航栏按钮
        
        // 无法高亮
//        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "好友", style: .plain, target: self, action: #selector(showFriends))
        
        // swift 调用OC 返回的instance方法，判断不出是否可选
//        let btn:UIButton = UIButton.cz_textButton("好友", fontSize: 16, normalColor: UIColor.darkGray, highlightedColor: UIColor.orange)
//        btn.addTarget(self, action: #selector(showFriends), for: .touchUpInside)
//        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)
 
//        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "好友", fontSize: 16, target: self, action: #selector(showFriends))
        navItem.leftBarButtonItem = UIBarButtonItem(title: "好友", fontSize: 16, target: self, action: #selector(showFriends))
        
        // 注册原型 cell
        tableView?.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        setupNavTitle()
    }
    
    /// 设置导航栏标题
    fileprivate func setupNavTitle() {
        let title = WBNetworkManager.shared.userAccont.screen_name
        let button = WBTitleButton(title: title)
        button.addTarget(self, action: #selector(clickTitleButton), for: .touchUpInside)
        navItem.titleView = button 
    }
    @objc func clickTitleButton(btn: UIButton) {
        btn.isSelected = !btn.isSelected
    }
}
